package com.piece.admin.config;

import com.piece.core.web.constants.WsConstants;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * 配置WebSocket
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketAutoConfig implements WebSocketMessageBrokerConfigurer {

	/**
	 * 注册STOMP协议的节点(endpoint),并映射指定的url
     */
	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		//注册STOMP的endpoint,并指定使用SockJS协议
		registry.addEndpoint(WsConstants.ENDPOINT_STOMP).setAllowedOriginPatterns("*").addInterceptors().withSockJS();
	}

	/**
	 * 配置消息代理(Message Broker)
	 */
	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
		//点对点应配置一个/user消息代理，广播式应配置一个/topic消息代理
		registry.enableSimpleBroker("/topic", "/chat", "/user", "/all");
		//客户端向服务端发送消息需有/app 前缀
		registry.setApplicationDestinationPrefixes("/app");
		//点对点使用的订阅前缀（客户端订阅路径上会体现出来），不设置的话，默认也是/user/
		registry.setUserDestinationPrefix("/user");
	}

	/**
	 * 开启WebSocket协议支持
	 * TODO 使用外置tomcat需要注释掉
	 */
	@Bean
	@ConditionalOnMissingBean(ServerEndpointExporter.class)
	public ServerEndpointExporter endpointExporter() {
		return new ServerEndpointExporter();
	}
}
